import myAxios from '../myAxios/myAxios.js';
import myAxios28 from '../myAxios/myAxios28.js';

let GetStockCountTable = async function (metCodeParamString) {
	const testMatnr = "E0010108X";
	// 查询数据库
	let param = `Q902🈹3001,3002,3003,3006,1007,1008,7001,9201🈹${metCodeParamString}🈹A🈹X`;
	let stockCountTableQ902 = await myAxios.getSap("SAP库存（单物料,包含未释放订单）2", param, 'Q902');
	let stockCountTableW902 = await myAxios.getSap("SAP库存（单物料,包含未释放订单）2", 'W902' + param.substring(4), 'Q902');
	let table = [];
	table.push(...stockCountTableQ902.TableSet['返回表']);
	table.push(...stockCountTableW902.TableSet['返回表']);

	const groupedObj = table.reduce((acc, currentRow) => {
		const groupKey = `${currentRow.MATNR}_${currentRow.MAKTX}`;

		if (!acc[groupKey]) {
			acc[groupKey] = [];
		}

		acc[groupKey].push(currentRow);
		return acc;
	}, {});

	// 2. 处理每个分组，进行聚合操作
	const resultArray = [];
	let keys = Object.keys(groupedObj);
	let matcodeWGZ_Dic = await getWGZCount();
	for (let i = 0; i < keys.length; i++) {
		const key = keys[i];
		const group = groupedObj[key];
		const firstRow = group[0];

		let count = matcodeWGZ_Dic[firstRow.MATNR] || 0;
		// 3. 创建新对象，包含聚合后的数据
		const newRow = {
			MATNR: firstRow.MATNR,
			MAKTX: firstRow.MAKTX,
			// 计算LABST的和并减去GetWGZCount的值
			LABST: group.reduce((sum, r) => sum + parseInt(r.LABST || 0, 10), 0) - count,
			// 找出RSMNG的最大值
			RSMNG: Math.max(...group.map(r => parseInt(r.RSMNG || 0, 10)))
		};
		resultArray.push(newRow);
	}

	const rowsSS = resultArray.filter(row => row.MATNR === testMatnr);
	console.log('GetStockCountTable :>> ', resultArray);
	return resultArray;
};
let getWGZCount = async function () {
	let matcodeWGZ_Dic = {}; // 未过账字典
	const sapData = await myAxios.getSap("SAP交货单号(工厂，物料)", `Q902🈹${''}`, "9901", "QD");
	const dataArray = sapData.TableSet['返回表'];

	// 使用数组的reduce方法进行groupBy操作
	matcodeWGZ_Dic = dataArray.reduce((accumulator, currentRow) => {
		// 检查REF_DOC是否以'033'开头
		if (currentRow.REF_DOC && currentRow.REF_DOC.startsWith('033')) {
			// 转换DLV_QTY为数字，处理可能的空值或非数字字符串
			const count = parseFloat(currentRow.DLV_QTY) || 0;
			const ADRNR = currentRow.ADRNR || '';

			// 根据ADRNR的值进行不同的处理（注释掉了C#中向不同字典添加的逻辑，按需实现）
			if (ADRNR.includes('24464')) {
				// 塑机逻辑 (原C#代码被注释)
				// 可在此处实现相应的JavaScript逻辑，例如更新某个对象
			} else if (ADRNR.includes('24932')) {
				// 金属逻辑 (原C#代码被注释)
			} else {
				// 外销逻辑 (原C#代码被注释)
			}

			let matcode = currentRow.MATCODE;
			if (accumulator.hasOwnProperty(matcode)) {
				accumulator[matcode] += count;
			} else {
				accumulator[matcode] = count;
			}

			return accumulator; // 累加符合条件行的DLV_QTY
		} else {
			return accumulator; // 不符合条件，返回当前累加值
		}
	}, {});
	console.log('getWGZCount :>> ', matcodeWGZ_Dic);
	return matcodeWGZ_Dic; // 返回总和
};


export {
	GetStockCountTable
};